package com.mf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mf.model.po.RegisterPo;
import com.mf.model.vo.RegisterVo;
import com.mf.model.pojomapper.RegisterPojoConverter;
import com.mf.service.RegisterService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mf.model.ResultVo;
import com.mf.util.ResultBuilder;
import com.mf.util.PageUtil;
import com.mf.util.MfPage;
import com.mf.validation.ValidGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Max;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 接口
 */
@RestController
@RequestMapping("/v1")
@Validated
@Slf4j
public class RegisterController {

    @Value("${simon.file-upload-dir}")
    private String uploadDir;
    @Resource
    private RegisterService registerService;
    @Resource
    private RegisterPojoConverter registerPojoConverter;

    public ResultVo<MfPage<RegisterVo>> queryByPage(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "20") @Max(50) Integer pageSize) {
        final RegisterPo registerPo = new RegisterPo();
        final IPage<RegisterVo> page =
                registerService.queryByPage(registerPo, new Page<>(pageNum, pageSize)).convert(P -> registerPojoConverter.toVo(P));
        return ResultBuilder.success(PageUtil.buildPage(page));
    }

    /**
     * 新增一条报名记录
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("public/add")
    public ResultVo add(@Validated(value = ValidGroup.Crud.Create.class)
                        @RequestBody RegisterVo registerVo) {
        final RegisterPo exist = registerService.querySingle(new LambdaQueryWrapper<RegisterPo>().eq(RegisterPo::getIdCard, registerVo.getIdCard()));
        if (Objects.nonNull(exist)) {
           registerService.updateById(registerPojoConverter.toPo(registerVo).setId(exist.getId()));
        }else {
            this.registerService.insert(registerPojoConverter.toPo(registerVo));
        }
        return ResultBuilder.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVo edit(@Validated(value = ValidGroup.Crud.Update.class)
                         @RequestBody RegisterVo registerVo) {
        this.registerService.updateById(registerPojoConverter.toPo(registerVo));
        return ResultBuilder.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVo deleteById(@RequestParam(name = "id") Long id) {
        this.registerService.deleteById(id);
        return ResultBuilder.success();
    }

    @PostMapping("/public/upload/photo")
    public ResultVo<String> uploadPhoto(MultipartFile photo, HttpServletRequest req) throws IOException {
        String format = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String path = req.getServletContext().getRealPath("/") + format;
        File folder = new File(path);
        //判断文件是否存在,不存在，则创建
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //2、处理文件名
        //获取文件后缀+文件名
        String oldName = photo.getOriginalFilename();
        //将后缀加到新的文件名上
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        //文件保存
        final File targetFile = new File(uploadDir, newName);
        log.info("try to transfer to {}", targetFile.getAbsolutePath());
        photo.transferTo(targetFile);
        //获取请求协议                            获取主机名                       获取端口
        String url = req.getScheme() + "://118.31.68.15/media/" + newName;//文件的访问路径
        return ResultBuilder.success(url);
    }

}

